package stage1.module4.Q3;

public class TicketRunnable implements Runnable {

    private int ticket;

    public TicketRunnable(int ticket) {
        this.ticket = ticket;
    }

    public int getTicket() {
        return ticket;
    }

    @Override
    public void run() {
        long id = Thread.currentThread().getId();
        while (true) {
            synchronized (this) {
                if (ticket > 0) {
                    // 锁定卖票过程，使得同一时间，只有一个线程能够执行卖票
                    ticket--;
                    System.out.println("线程 " + id + " 卖出一张票，剩余票数：" + ticket);
                }
                else {
                    break;
                }
            }
        }
        System.out.println("票已卖完，线程 " + id + " 停止卖票。");
    }
}
